package example

import (
	"errors"
	"github.com/flipped-aurora/gin-vue-admin/server/api/v1/common"
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/avatar"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/example"
	"github.com/flipped-aurora/gin-vue-admin/server/utils/upload"
	"github.com/gin-gonic/gin"
	"mime/multipart"
	"strings"
)

//@author: [piexlmax](https://github.com/piexlmax)
//@function: Upload
//@description: 创建文件上传记录
//@param: file model.ExaFileUploadAndDownload
//@return: error

func (e *FileUploadAndDownloadService) Upload(file example.ExaFileUploadAndDownload) error {
	return global.GVA_DB.Create(&file).Error
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: FindFile
//@description: 查询文件记录
//@param: id uint
//@return: model.ExaFileUploadAndDownload, error

func (e *FileUploadAndDownloadService) FindFile(id uint) (example.ExaFileUploadAndDownload, error) {
	var file example.ExaFileUploadAndDownload
	err := global.GVA_DB.Where("id = ?", id).First(&file).Error
	return file, err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: DeleteFile
//@description: 删除文件记录
//@param: file model.ExaFileUploadAndDownload
//@return: err error

func (e *FileUploadAndDownloadService) DeleteFile(file example.ExaFileUploadAndDownload) (err error) {
	var fileFromDb example.ExaFileUploadAndDownload
	fileFromDb, err = e.FindFile(file.ID)
	if err != nil {
		return
	}
	oss := upload.NewOss()
	if err = oss.DeleteFile(fileFromDb.Key); err != nil { //有了key，也可以同时删除avatar表中的数据
		return errors.New("文件删除失败")
	}
	if err = global.GVA_DB.Where("id = ?", file.ID).Unscoped().Delete(&file).Error; err != nil {
		return err
	}
	//这个地方加上了删除
	err = global.GVA_DB.Where("avatar_position = ?", file.Key).Unscoped().Delete(&avatar.Avatar{}).Error
	return err
}

// EditFileName 编辑文件名或者备注
func (e *FileUploadAndDownloadService) EditFileName(file example.ExaFileUploadAndDownload) (err error) {
	var fileFromDb example.ExaFileUploadAndDownload
	txdb := global.GVA_DB.Begin()
	if err := txdb.Where("id = ?", file.ID).First(&fileFromDb).Update("name", file.Name).Error; err != nil {
		txdb.Rollback()
		return err
	}
	var tempFile example.ExaFileUploadAndDownload
	if err := txdb.Where("id = ?", file.ID).First(&tempFile).Error; err != nil {
		txdb.Rollback()
		return err
	}
	var tempAvatar avatar.Avatar
	if err = txdb.Where("avatar_position = ?", tempFile.Key).First(&tempAvatar).Update("avatar_position", file.Key).Error; err != nil {
		txdb.Rollback()
		return err
	}
	txdb.Commit()
	return
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: GetFileRecordInfoList
//@description: 分页获取数据
//@param: info request.PageInfo
//@return: list interface{}, total int64, err error

func (e *FileUploadAndDownloadService) GetFileRecordInfoList(info request.PageInfo) (list interface{}, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	keyword := info.Keyword
	db := global.GVA_DB.Model(&example.ExaFileUploadAndDownload{})
	var fileLists []example.ExaFileUploadAndDownload
	if len(keyword) > 0 {
		db = db.Where("name LIKE ?", "%"+keyword+"%")
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Limit(limit).Offset(offset).Order("updated_at desc").Find(&fileLists).Error
	return fileLists, total, err
}

func (e *FileUploadAndDownloadService) GetFileRecordInfoListCommon(info request.PageInfo, c *gin.Context) (list interface{}, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	keyword := info.Keyword
	db := global.GVA_DB.Model(&example.ExaFileUploadAndDownload{})
	key, _ := c.Get("userID")
	var tempStoreA []avatar.Avatar
	var position []string
	global.GVA_DB.Where("avatar_user = (?)", key.(uint)).Find(&tempStoreA)
	for i := 0; i < len(tempStoreA); i++ {
		position = append(position, tempStoreA[i].Avatar_position)
	}
	var fileLists []example.ExaFileUploadAndDownload

	if len(keyword) > 0 {
		db = db.Where("name LIKE ?", "%"+keyword+"%")
	}
	db = db.Where("exa_file_upload_and_downloads.key in ?", position)
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Limit(limit).Offset(offset).Order("updated_at desc").Find(&fileLists).Error
	return fileLists, total, err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: UploadFile
//@description: 根据配置文件判断是文件上传到本地或者七牛云
//@param: header *multipart.FileHeader, noSave string
//@return: file model.ExaFileUploadAndDownload, err error

func (e *FileUploadAndDownloadService) UploadFile(header *multipart.FileHeader, noSave string) (file example.ExaFileUploadAndDownload, err error) {
	oss := upload.NewOss()
	filePath, key, uploadErr := oss.UploadFile(header)
	if uploadErr != nil {
		panic(err)
	}
	if noSave == "0" {
		s := strings.Split(header.Filename, ".")
		f := example.ExaFileUploadAndDownload{
			Url:  filePath,
			Name: header.Filename,
			Tag:  s[len(s)-1],
			Key:  key,
		}
		return f, e.Upload(f)
	}
	return
}

func (e *FileUploadAndDownloadService) UploadFileWithUserId(header *multipart.FileHeader, noSave string, userId uint) (file example.ExaFileUploadAndDownload, err error) {
	oss := upload.NewOss()
	filePath, key, uploadErr := oss.UploadFile(header)
	if uploadErr != nil {
		panic(err)
	}
	if noSave == "0" {
		s := strings.Split(header.Filename, ".")
		f := example.ExaFileUploadAndDownload{
			Url:  filePath,
			Name: header.Filename,
			Tag:  s[len(s)-1],
			Key:  key,
		}
		//这个地方再插进来存入图片路径的逻辑
		if err := common.CreateAvatarD(userId, f.Key); err != nil {
			return f, err
		}
		return f, e.Upload(f)
	}
	return
}
